// db.ts
interface Collection {
  id?: number;
  name: string;
}

const DB_NAME = 'SimpleCollectionDB';
const DB_VERSION = 1;
const STORE_NAME = 'collections';

class CollectionDB {
  private db: IDBDatabase | null = null;

  async open(): Promise<IDBDatabase> {
    return new Promise<IDBDatabase>((resolve, reject) => {
      const request = indexedDB.open(DB_NAME, DB_VERSION);

      request.onerror = () => reject(request.error);
      request.onsuccess = () => {
        this.db = request.result;
        resolve(this.db);
      };

      request.onupgradeneeded = (event: IDBVersionChangeEvent) => {
        const db = (event.target as IDBOpenDBRequest).result;
        if (!db.objectStoreNames.contains(STORE_NAME)) {
          db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
        }
      };
    });
  }

  // 新增集合
  async add(data: Omit<Collection, 'id'>): Promise<number> {
    await this.open();
    return new Promise<number>((resolve, reject) => {
      const transaction = this.db!.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.add({ ...data });

      request.onsuccess = () => resolve(request.result as number);
      request.onerror = () => reject(request.error);
    });
  }

  // 查询所有集合
  async getAll(): Promise<Collection[]> {
    await this.open();
    return new Promise<Collection[]>((resolve, reject) => {
      const transaction = this.db!.transaction([STORE_NAME], 'readonly');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.getAll();

      request.onsuccess = () => {
        const result = request.result;
        // 确保 id 为 number 类型
        resolve(result.map(item => ({ ...item, id: Number(item.id) })));
      };
      request.onerror = () => reject(request.error);
    });
  }

  // 更新集合
  async update(data: Collection): Promise<void> {
    await this.open();
    return new Promise<void>((resolve, reject) => {
      const transaction = this.db!.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.put({ ...data });

      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  }

  // 删除集合
  async delete(id: number): Promise<void> {
    await this.open();
    return new Promise<void>((resolve, reject) => {
      const transaction = this.db!.transaction([STORE_NAME], 'readwrite');
      const store = transaction.objectStore(STORE_NAME);
      const request = store.delete(id);

      request.onsuccess = () => resolve();
      request.onerror = () => reject(request.error);
    });
  }
}

export const collectionDB = new CollectionDB();
export type { Collection };